package com.fred.util

import com.fred.bean.PhoneBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader

object AdbUtil {
    val adbFilePath by lazy {
        val rootPath = Util.resourcesPath
        "$rootPath"
    }
    suspend fun getDevices():ArrayList<PhoneBean> = withContext(Dispatchers.IO){
        val result = arrayListOf<PhoneBean>()
        val adbFile = File("${adbFilePath}${File.separator}adb.exe")
        if (adbFile.exists()){
            val process = ProcessBuilder().command("${adbFile.absolutePath} ","devices","-l")
                .start()
            val successResult = BufferedReader(InputStreamReader(process.inputStream))
            var read: String?
            while (successResult.readLine().also { read = it } != null) {
                val device = handleDevice(read)
                if (device != null){
                    result.add(device)
                }
            }
        }
        result
    }

   private fun handleDevice(device:String?):PhoneBean?{
        val d = device?.trim()?:return null
       if (d.startsWith("List of devices")) return null
        val rs = d.split(" ")
        val usbName = rs[0].trim()
        if (usbName.isNotEmpty()){
            val phoneBean = PhoneBean(usbName)
            rs.forEach {
                if (it.trim().isNotEmpty()) {
                    if (it == "offline") {
                        return null
                    }
                    if (it.startsWith("product:")) {
                        phoneBean.deviceProduct = it.substring(8).trim()
                    }
                    if (it.startsWith("model:")) {
                        phoneBean.model = it.substring(6).trim()
                    }
                    if (it.startsWith("device:")) {
                        phoneBean.device = it.substring(7).trim()
                    }
                    if (it.startsWith("transport_id:")) {
                        try {
                            phoneBean.transportId =  it.substring(13).trim().toInt()
                        }catch (e:Exception){
                            phoneBean.transportId = 0
                        }
                    }
                }
            }
            return phoneBean
        }
       return null
    }

}
